package net.freebytes.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

public class HelloWorldClient2 {

    public static void main(String[] args) throws InterruptedException {
        // 客户端引导器
        Bootstrap bootstrap = new Bootstrap();
        // 配置线程组
        bootstrap.group(new NioEventLoopGroup());
        // 指定 IO 类型为 NIO
        bootstrap.channel(NioSocketChannel.class);
        // 配置 IO 处理器
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new StringEncoder());
            }
        });
        // 建立连接
        Channel channel = bootstrap.connect("127.0.0.1", 8081).channel();
        // 发送消息
//        while (true) {
            channel.writeAndFlush(Unpooled.copiedBuffer(tring()));
//            TimeUnit.SECONDS.sleep(100);
        channel.close();
//        }
    }

    private static byte[] tring() {
        String hexString = "6810000000000068110433333433C216";
        byte[] byteArray = new byte[hexString.length() / 2];

        for (int i = 0; i < byteArray.length; i++) {
            // 每两个字符代表一个字节
            String byteString = hexString.substring(i * 2, i * 2 + 2);
            // 将十六进制字符串转换为整数
            int byteValue = Integer.parseInt(byteString, 16);
            // 将整数转换为字节并赋值给数组
            byteArray[i] = (byte) (byteValue & 0xFF); // 确保值在byte范围内
        }

// 打印结果
        for (byte b : byteArray) {
            System.out.print(b & 0xFF);
        }
        return byteArray;
    }

}
